# -*- coding:utf-8 -*-
"""
Created on 26 aug 2012

@author: Olof Manbo
"""

from google.appengine.ext import webapp
from django.utils import simplejson

import logging
import re

import requests
import test_pb2
import contour
import random
import time

class Page(webapp.RequestHandler):
    def get(self):


        html = """
        <!DOCTYPE html>
            <html>
            <head>
            <title>Fursten karta</title>
            <style>
                %s
            </style>
            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
            <script src="http://d3js.org/d3.v2.js"></script>
            <script>
            
            function MouseWheelHandler(e) {  
                // cross-browser wheel delta  
                var e = window.event || e; // old IE support  
                var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
                console.log(delta); 
                }
                function run_script() {
                    var svg = d3.select("svg").style("background-color", "grey");

                    var path = d3.selectAll("#mappath")
                    .attr("transform", "translate(500 500) scale(0.05)");
                    
                        // IE9, Chrome, Safari, Opera  
                    $("svg").addEventListener("mousewheel", MouseWheelHandler, false);  
                   // Firefox  
                   //svg.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
                }
            </script>
            </head>
            <body onload="run_script()">
                <svg id="map" width="1000" height="1000">
                  %s
                  %s
              </svg>
              <svg id=coords" width="1000" height="1000">
                %s
                %s
             </svg>
            </body>
        </html>
        """
        SCALE = 200
        X=range(-50,50)
        Y=range(-50,50)
        allNodes = self.getNodes()
        node_names = ["vegetation_24trees", "vegetation_24grass", "hydrology_surfacewater"]
        nodes = [allNodes[node_name] for node_name in node_names]
        svg, real_data = contour.getSvg(SCALE, nodes, node_names , X, Y)
        cssData = self.getCssData()
        circles = ""
        for name, nodes in zip(node_names, nodes):
            for node in nodes:
                circles += '<circle cx="%i", cy="%i", r="100" stroke-width="10" class="%s" transform="translate(500 500) scale(0.05)"></circle>\n'%(node[0], node[1], "node_%s"%name)
#        
#        for x in X:
#            for y in Y:
#                circles += '<circle cx="%i", cy="%i", r="10" stroke-width="1" fill="black" stroke="black" transform="translate(500 500) scale(0.05)"></circle>\n'%(x*SCALE, y*SCALE)
        circles2 = ""        
        for x in X:
            for y in Y:
                if real_data[x + 50][y + 50] > 0:
                    node_name = node_names[real_data[x + 50][y + 50]-1]
                    circles2 += '<circle cx="%i", cy="%i", r="100" stroke-width="1" class="%s" transform="translate(500 500) scale(0.05)"></circle>\n'%(x*SCALE, y*SCALE, "node_%s"%node_name)
        html = html%(cssData, svg, circles, circles2, circles)
        
        self.response.out.write(html)             

    def getNodeNames(self):
        stuff = requests.sendResourceXmlRequest("localhost:8888")
        return stuff.values()
        
    def getNodes(self):
        t0 = time.time()
        stuff = requests.sendResourceXmlRequest("localhost:8888")
        logging.info(stuff)
        nodeResponse = requests.sendNodeRequest("localhost:8888")
        nodes = {}
        for node in nodeResponse.node:
            key = stuff[node.resource_key]
            if nodes.has_key(key):
                nodes[key].append([node.x, node.y])
            else:
                nodes[key] = [[node.x, node.y]]
        logging.info("getNodes() time:%f"%(time.time() - t0))
        return nodes
    
    def getCssData(self):
        t0 = time.time()
        cssdata = requests.sendFurstenCssRequest("localhost:8888")
        
        for line in cssdata.splitlines():
            m = re.match(r"#(.*)\{.*color:(#.{6}).*", line)
            if (m is not None):
                cssdata += "\n#line_%s{stroke: %s;}"%(m.group(1), m.group(2))
            m = re.match(r"\.(.*?)-.*border-color:(#.{6}).*color:(#.{6}).*", line)    
            if (m is not None):
                cssdata += "\n.node_%s{stroke: %s; fill: %s;}"%(m.group(1), m.group(2), m.group(3))
        logging.info("getCssData() time:%f"%(time.time() - t0))
        return cssdata